﻿@page "/sync"
@inject ISyncSessionStorageService sessionStorage

<h1>Non Async Session Storage</h1>

<div class="row mb-5">

    <div class="col-md-4">
        <h5>Add Item to session storage</h5>
        <div class="input-group">
            <input class="form-control" type="text" placeholder="Enter a value" @bind="Name" />
            <div class="input-group-append">
                <button class="btn btn-primary" @onclick="SaveName">Save</button>
            </div>
        </div>
    </div>

    <div class="col-md-4">
        <h5>Remove item from session storage</h5>
        <button class="btn btn-primary" @onclick="RemoveName">Remove Item</button>
    </div>

    <div class="col-md-4">
        <h5>Clear session storage</h5>
        <button class="btn btn-primary" @onclick="ClearSessionStorage">Clear All</button>
    </div>
</div>

<div class="row">

    <div class="col-md-4">
        <h5>Value Read from session storage</h5>
        @NameFromSessionStorage
    </div>

    <div class="col-md-4">
        <h5>Items in session storage</h5>
        @ItemsInSessionStorage
    </div>
</div>

@code {

    string NameFromSessionStorage { get; set; }
    int ItemsInSessionStorage { get; set; }
    string Name { get; set; }

    protected override void OnInitialized()
    {
        GetNameFromSessionStorage();
        GetSessionStorageLength();

        sessionStorage.Changed += (sender, e) =>
        {
            Console.WriteLine($"Value for key {e.Key} changed from {e.OldValue} to {e.NewValue}");
        };
    }

    void SaveName()
    {
        sessionStorage.SetItem("name", Name);
        GetNameFromSessionStorage();
        GetSessionStorageLength();

        Name = "";
    }

    void GetNameFromSessionStorage()
    {
        NameFromSessionStorage = sessionStorage.GetItem<string>("name");

        if (string.IsNullOrEmpty(NameFromSessionStorage))
        {
            NameFromSessionStorage = "Nothing Saved";
        }
    }

    void RemoveName()
    {
        sessionStorage.RemoveItem("name");
        GetNameFromSessionStorage();
        GetSessionStorageLength();
    }

    void ClearSessionStorage()
    {
        Console.WriteLine("Calling Clear...");
        sessionStorage.Clear();
        Console.WriteLine("Getting name from session storage...");
        GetNameFromSessionStorage();
        Console.WriteLine("Calling Get Length...");
        GetSessionStorageLength();
    }

    void GetSessionStorageLength()
    {
        Console.WriteLine(sessionStorage.Length());
        ItemsInSessionStorage = sessionStorage.Length();
    }

}
